<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command;

use app\model\CrontabTaskModel;
use app\model\FileUploadModel;
use app\model\VideoModel;
use app\model\VideoRelationModel;
use app\model\WorkflowStep;
use app\model\ZcStoreModel;
use app\model\ZcSubtasksMemberModel;
use app\model\ZcTaskModel;
use think\console\Input;
use think\console\Output;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;

/*
 * 缓存视频员工关系
 */

class CacheVideoRelationWork extends BaseWork implements DailyStatWork
{
    public ?int $tag = null;

    public function setTag($tag = null): bool
    {
        if (! is_null($tag)) {
            $this->tag = $tag;
        }
        return true;
    }

    public function getTag(): ?string
    {
        return strval($this->tag);
    }

    public function getCommandName(): string
    {
        return $this->getName();
    }

    /**
     * 获取定时任务.
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getCrontabTaskInfo(): CrontabTaskModel
    {
        $where = [
            ['task_name', '=', $this->getName()],
            //            ['tag', '=', $this->getTag()],
        ];

        $obj = new CrontabTaskModel();
        $model = $obj->where($where)->field(true)->find();
        return $model instanceof CrontabTaskModel ? $model : $obj;
    }

    protected function configure()
    {
        // 指令配置
        $this->setName('cache_video_relation_work');
        // 设置参数
        $this->setDescription('缓存视频员工关系')
            ->setHelp('php think cache_video_relation_work');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        ini_set('memory_limit', '500M');
        $this->setTag();
        $output->writeln('=======缓存视频员工关系开始' . date('Y-m-d H:i:s', time()) . '=======');
        $allVideo = VideoModel::alias('a')
            ->leftJoin(['habo_video_relation' => 'b'], 'a.file_id=b.file_id')
            ->whereNull('b.id')
            ->field('a.file_id,a.task_id,a.subtask_id,a.company_id')
            ->select()->toArray();
        try {
            foreach ($allVideo as $video) {
                // 查询是否已存在
                $isHas = VideoRelationModel::where('file_id', $video['file_id'])
                    ->value('id');
                if ($isHas) {
                    continue;
                }
                $file = FileUploadModel::where('id', $video['file_id'])->find();
                if (! $file) {
                    continue;
                }
                $data = [
                    'file_id' => $video['file_id'],
                    'staff_id' => $file['create_staff_id'],
                    'company_id' => $video['company_id'],
                ];
                if ($video['task_id'] > 0) {
                    $task = ZcTaskModel::where('id', $video['task_id'])->find();
                    if ($task) {
                        $data['operation_id'] = $task['create_uid'];
                        $data['creative_team_id'] = $task['team_id'];
                        // 查询创意部门
                        $store = ZcStoreModel::where('id', $task['store_id'])->find();
                        if ($store) {
                            $data['creative_department_id'] = $store['department_id'];
                            $data['company_id'] = $store['company_id'];
                        }
                        // 查询任务参与人员
                        $taskMember = ZcSubtasksMemberModel::where('subtask_id', $video['subtask_id'])->select();
                        if ($taskMember) {
                            foreach ($taskMember as $val) {
                                // 查询流程
                                $role = WorkflowStep::where('workflow_id', $val['workflow_id'])
                                    ->where('step_position', $val['workflow_step_id'])->value('step_role');
                                if ($role) {
                                    $data['role_id'] = $role;
                                }
                                $data['staff_id'] = $val['user_id'];
                                VideoRelationModel::create($data);
                            }
                        }
                    }
                } else {
                    // 非任务流转，运营直接上传
                    $data['operation_id'] = $file['create_staff_id'];
                    VideoRelationModel::create($data);
                }
            }
        } catch (Exception $e) {
            dump($e);
        }

        $output->writeln('=======缓存视频员工关系结束' . date('Y-m-d H:i:s', time()) . '=======');
    }
}
